package com.github.livebase.log;

import android.text.TextUtils;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.UnknownHostException;

/**
 * @ClassName LFormat
 * @description:
 * @author: biao532
 * @create: 2024-02-05 20:27
 * @Version 1.0
 **/
public class LFormatter implements Formatter {
    private static Formatter formatter;
    public static Formatter getFormatter() {
        if (formatter == null) {
            synchronized (LFormatter.class) {
                if (null == formatter) {
                    formatter = new LFormatter();
                }
            }
        }
        return formatter;
    }
    protected LFormatter() {}
    @Override
    public String format(Throwable throwable, String format, Object... params) {
        if (throwable == null) {
            return this.format(format, params);
        }
        return getMessage(this.format(format, params), throwable);
    }

    @Override
    public String format(String format, Object... params) {
        StringBuilder builder = new StringBuilder();
        int idx = -1;
        int old = 0;
        int i = 0;
        while ((idx = format.indexOf("{}", old)) != -1) {
            builder.append(format.substring(old, idx));
            if (i < params.length) {
                builder.append(params[i++]);
            }
            old = idx + 2;
        }
        {}
        if (old < format.length()) {
            builder.append(format.substring(old));
        }
        return builder.toString();
    }

    private String getMessage(String message, Throwable throwable) {
        if (TextUtils.isEmpty(message)) {
            return getStackTraceString(throwable);
        }
        return message + "\n" + getStackTraceString(throwable);
    }

    private String getStackTraceString(Throwable tr) {
        if (tr == null) {
            return "";
        }

        // This is to reduce the amount of log spew that apps do in the non-error
        // condition of the network being unavailable.
        Throwable t = tr;
        while (t != null) {
            if (t instanceof UnknownHostException) {
                return "";
            }
            t = t.getCause();
        }

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        tr.printStackTrace(pw);
        pw.flush();
        return sw.toString();
    }
}
